﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
using LocalServerApp;
using System.ServiceModel.Channels;
using System.Net;

namespace LocalServerApp
{
    class Program
    {
        static void Main(string[] args)
        {
            IPAddress[] a = Dns.GetHostByName(Dns.GetHostName()).AddressList;

            //Uri baseAdress = new Uri("net.tcp://" + a[0] + ":8000/LocalServerApp/Service");
            Uri baseAdress = new Uri("net.tcp://localhost:8000/LocalServerApp/Service");
            ServiceHost serviceHost = new ServiceHost(typeof(LocalServerService), baseAdress);
            
            try
            {
                NetTcpBinding binding = new NetTcpBinding();
                NetTcpSecurity security = new NetTcpSecurity();
                security.Mode = SecurityMode.None;
                binding.Security = security;
                OptionalReliableSession rel = new OptionalReliableSession();
                rel.InactivityTimeout = TimeSpan.MaxValue;
                binding.ReliableSession = rel;
                binding.ReceiveTimeout = TimeSpan.MaxValue;

                serviceHost.AddServiceEndpoint(typeof(ILocalServerService), binding, "Service");
                
                #region WSDL
                //Allows the WSDL to be downloaded.
                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.MetadataExporter.PolicyVersion = PolicyVersion.Default;
                serviceHost.Description.Behaviors.Add(smb);
                #endregion

                serviceHost.AddServiceEndpoint(typeof(IMetadataExchange),
                                            MetadataExchangeBindings.CreateMexTcpBinding(), "mex");

                serviceHost.Open();
                displayHostInfo(serviceHost);

                Console.WriteLine("Service ready");
                Console.WriteLine("Press enter to terminate");
                Console.ReadLine();

                serviceHost.Close();
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
                serviceHost.Abort();
            }
            Console.ReadLine();
        }

        static void displayHostInfo(ServiceHost serviceHost)
        {
            Console.WriteLine("************ HOST INFO *************");
            foreach (System.ServiceModel.Description.ServiceEndpoint se in serviceHost.Description.Endpoints)
            {
                Console.WriteLine("Address: {0}", se.Address);
                Console.WriteLine("Binding: {0}", se.Binding.Name);
                Console.WriteLine("Contract: {0}", se.Contract.Name);
            }
            Console.WriteLine("************************************");

            Console.WriteLine();
        }
    }
}